package com.zbkj.crmeb.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.crmeb.core.utils.RedisUtil;
import com.utils.RestTemplateUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.enums.logistics.DeliveryChannelEnum;
import com.zbkj.crmeb.enums.logistics.DeliverySignStatusEnum;
import com.zbkj.crmeb.enums.logistics.LogisticsTypeEnum;
import com.zbkj.crmeb.export.vo.LogisticsExcelVo;
import com.zbkj.crmeb.express.model.Express;
import com.zbkj.crmeb.express.service.ExpressService;
import com.zbkj.crmeb.express.service.LogisticService;
import com.zbkj.crmeb.express.vo.LogisticsResultListVo;
import com.zbkj.crmeb.express.vo.LogisticsResultVo;
import com.zbkj.crmeb.sms.service.SmsService;
import com.zbkj.crmeb.store.dao.OrderInfoDeliveryDao;
import com.zbkj.crmeb.store.dao.StoreOrderInfoDao;
import com.zbkj.crmeb.store.model.OrderInfoDelivery;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.model.StoreOrderStatus;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.request.DeliveryRequest;
import com.zbkj.crmeb.store.request.GetOrderDeliveryListRequest;
import com.zbkj.crmeb.store.request.OrderInfoDeliveryRequest;
import com.zbkj.crmeb.store.request.StoreOrderSendRequest;
import com.zbkj.crmeb.store.response.DeliveryResponse;
import com.zbkj.crmeb.store.response.DeliveryResponse.DeliveryInfo;
import com.zbkj.crmeb.store.response.OrderDeliveryCountItemResponse;
import com.zbkj.crmeb.store.response.OrderDeliveryItemResponse;
import com.zbkj.crmeb.store.response.OrderDeliveryResponse;
import com.zbkj.crmeb.store.response.OrderDeliveryTopItemResponse;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.service.OrderInfoDeliveryService;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.service.StoreOrderStatusService;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import com.zbkj.crmeb.system.service.SystemAdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 * @author cyz
 * @date 2021/4/9 18:04
 */
@Slf4j
@Service
public class OrderInfoDeliveryServiceImpl extends ServiceImpl<OrderInfoDeliveryDao, OrderInfoDelivery> implements OrderInfoDeliveryService {

    @Resource
    private OrderInfoDeliveryDao dao;
    @Value("${showapi.appid}")
    private String appId;
    @Value("${showapi.secret}")
    private String secret;

    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Autowired
    private ExpressService expressService;

    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    SmsService smsService;

    @Resource
    private StoreOrderInfoDao storeOrderInfoDao;

    @Autowired
    StoreOrderService storeOrderService;

    @Autowired
    StoreOrderInfoService storeOrderInfoService;

    @Autowired
    IChannelMerchantService channelMerchantService;

    @Autowired
    SupplierService supplierService;

    @Autowired
    SystemAdminService systemAdminService;

    @Autowired
    private StoreOrderStatusService storeOrderStatusService;

    @Resource
    private LogisticService logisticService;


    /**
     * 
     * @author cyz
     * @date 2021/4/9 18:19
     * @param request 
     * @return java.util.List<com.zbkj.crmeb.store.model.OrderInfoDelivery>
     */
    @Override
    public List<OrderInfoDelivery> getDeliveryList(OrderInfoDeliveryRequest request) {
        LambdaQueryWrapper<OrderInfoDelivery> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(request.getDeliveryNumber())){
            lambdaQueryWrapper.eq(OrderInfoDelivery::getDeliveryNumber, request.getDeliveryNumber());
        }
        lambdaQueryWrapper.ne(OrderInfoDelivery::getChannel,5);
        lambdaQueryWrapper.eq(OrderInfoDelivery::getOrderInfoId, request.getOrderInfoId());
        lambdaQueryWrapper.orderByDesc(OrderInfoDelivery::getLevel);
        if (Objects.isNull(request.getIsExchange())) {
            lambdaQueryWrapper.and(e -> e.ne(OrderInfoDelivery::getIsExchange, 1).or().isNull(OrderInfoDelivery::getIsExchange));
        } else {
            lambdaQueryWrapper.eq(OrderInfoDelivery::getIsExchange, 1);
        }
        List<OrderInfoDelivery> list = dao.selectList(lambdaQueryWrapper);
        if (Objects.isNull(request.getIsExchange())) {
            if (CollectionUtils.isNotEmpty(list)) {
                StoreOrderInfo storeOrderInfo = storeOrderInfoDao.selectById(list.get(0).getOrderInfoId());
                if (Objects.isNull(storeOrderInfo)) {
                    throw new CrmebException("该订单不存在");
                }
                list.forEach(e -> {
                    LogisticsTypeEnum logisticsTypeName = getLogisticsTypeName(storeOrderInfo.getLogisticsType(), e.getChannel());
                    if(logisticsTypeName != null){
                        e.setLogisticsTypeName(logisticsTypeName.getMsg());
                        e.setLogisticsType(logisticsTypeName.getCode());
                    }
                });
            }
        }
        return list;
    }

    @Override
    public List<OrderInfoDelivery> getUserDeliveryList(OrderInfoDeliveryRequest request) {
        LambdaQueryWrapper<OrderInfoDelivery> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(request.getDeliveryNumber())){
            lambdaQueryWrapper.eq(OrderInfoDelivery::getDeliveryNumber, request.getDeliveryNumber());
        }
        lambdaQueryWrapper.eq(OrderInfoDelivery::getChannel,5);
        lambdaQueryWrapper.eq(OrderInfoDelivery::getOrderInfoId, request.getOrderInfoId());
        lambdaQueryWrapper.orderByDesc(OrderInfoDelivery::getLevel);
        return dao.selectList(lambdaQueryWrapper);
    }


    /**
     * 获取物流发货类型名称
     * @param type
     * @param channel
     * @return
     */
    private LogisticsTypeEnum getLogisticsTypeName(Integer type, Integer channel){
        if(!DeliveryChannelEnum.DELIVERY.getCode().equals(channel)){
            return LogisticsTypeEnum.DEFAULT;
        }
        return LogisticsTypeEnum.valueOf(type);
    }

    @Override
    public Integer addDelivery(OrderInfoDeliveryRequest request) {
        if(request.getChannel() == null){
            throw new CrmebException("操作方式不能为空!");
        }
        OrderInfoDelivery orderInfoDelivery = new OrderInfoDelivery();
        BeanUtils.copyProperties(request,orderInfoDelivery);
        return dao.insert(orderInfoDelivery);
    }

    @Override
    public Integer udpateDelivery(OrderInfoDeliveryRequest request) {
        if(request.getChannel() == null){
            throw new CrmebException("操作方式不能为空!");
        }
        OrderInfoDelivery delivery = dao.selectById(request.getId());
        if(null == delivery){
            throw new CrmebException("该物流信息不存在!");
        }
        if(null != delivery.getChannel() && !request.getChannel().equals(delivery.getChannel())){
            throw new CrmebException("只能修改自己添加的物流信息!");
        }
        OrderInfoDelivery orderInfoDelivery = new OrderInfoDelivery();
        BeanUtils.copyProperties(request,orderInfoDelivery);
        Express express = expressService.info(request.getExpressId());
        if(null!=express){
            orderInfoDelivery.setDeliveryCode(express.getCode());
            orderInfoDelivery.setDeliveryCompany(express.getName());
        }
        return dao.updateById(orderInfoDelivery);
    }

    /**
     * 请求万维快递
     * @author cyz
     * @date 2021/4/12 17:59
     * @param request 
     * @return com.zbkj.crmeb.store.response.DeliveryResponse
     */
    @Override
    public DeliveryResponse queryDeliveryByShowApi(DeliveryRequest request, OrderInfoDelivery orderInfoDelivery){
        DeliveryResponse deliveryResponse = (DeliveryResponse) redisUtil.get(request.getOrderInfoId()+"-"+request.getDeliveryNumber());
        if(null != deliveryResponse){
            return deliveryResponse;
        }
        // 1.1已签收
        if (DeliverySignStatusEnum.SIGN.getCode().equals(orderInfoDelivery.getSignStatus())){
            return convertOrderInfoDelivery(orderInfoDelivery);
        }
        // 1.2三小时内查询过
        if (Objects.nonNull(orderInfoDelivery.getQueryTime())
                && orderInfoDelivery.getQueryTime().after(DateUtil.addHour(new Date(), -3))){
            if (orderInfoDelivery.getQueryFlag()){
                return convertOrderInfoDelivery(orderInfoDelivery);
            }
            return null;
        }

        try {
            LogisticsResultVo info = logisticService.info(getExpressNo(request.getDeliveryNumber(),request.getPhone()), null);
            if (null == info){
                return null;
            }
            DeliveryResponse response = new DeliveryResponse();
            response.setFlag(true);
            response.setLogo(info.getLogo());
            response.setMailNo(info.getNumber());
            response.setTel(info.getExpPhone());
            response.setExpSpellName(info.getExpName());
            response.setExpTextName(info.getExpName());
            String[] data = new String[128];
            List<DeliveryInfo> deliveryInfos = new ArrayList<>();
            List<LogisticsResultListVo> list = info.getList();
            for (int i = 0; i < list.size(); i++) {
                DeliveryInfo deliveryInfo = new DeliveryInfo();
                LogisticsResultListVo logisticsResultListVo = list.get(i);
                deliveryInfo.setContext(logisticsResultListVo.getStatus());
                deliveryInfo.setTime(logisticsResultListVo.getTime());
                data[i] = JSON.toJSONString(deliveryInfo);
            }
            response.setData(data);
            // 更新物流API查询结果
            updateOrderInfoDelivery(orderInfoDelivery, response);
            if(response.isFlag()){
                response.setStatus(1);
                redisUtil.set(request.getOrderInfoId()+"-"+request.getDeliveryNumber(), response, 3L, TimeUnit.HOURS);
                return response;
            }
        }catch (Exception e){
            log.error("查询物流详情异常: ",e);
        }



//        // 1.3订单已完成已签收
//        StoreOrderInfo storeOrderInfo = storeOrderInfoDao.selectById(request.getOrderInfoId());
//        if (OrderStatusEnum.COMPLETE.getCode().equals(storeOrderInfo.getStatus())
//                && DeliverySignStatusEnum.SIGN.getCode().equals(orderInfoDelivery.getSignStatus())) {
//            DeliveryResponse response = convertOrderInfoDelivery(orderInfoDelivery);
////            response.setStatus(1);
//            return response;
//        }


//        String sign = getSign(request.getCom(),request.getDeliveryNumber(),request.getPhone());
//        String url = "";
//        if(StringUtils.isBlank(request.getPhone())){
//            url = "https://route.showapi.com/64-19?com="+request.getCom()+"&nu="+request.getDeliveryNumber()+"&showapi_appid="+appId+"&showapi_sign="+sign;
//        }else {
//            url = "https://route.showapi.com/64-19?com="+request.getCom()+"&nu="+request.getDeliveryNumber()+"&phone="+request.getPhone()+"&showapi_appid="+appId+"&showapi_sign="+sign;
//        }
//        try {
//            log.info("--------------- 开始请求万维易源查询快递信息 url: {},body:{} ---------------", url , JSONObject.toJSONString(request));
//            JSONObject jsonObject = restTemplateUtil.getData(url);
//            log.info("--------------- 请求万维易源查询快递信息返回结果: {} ---------------", jsonObject);
//            if("-2".equals(jsonObject.get("showapi_res_code").toString()) ){
//                smsService.sendLogisticsMessage();
//            }
//            if(Objects.isNull(jsonObject.get("showapi_res_body"))){
//                return null;
//            }
//            DeliveryResponse response = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("showapi_res_body")), DeliveryResponse.class);
//            // 更新物流API查询结果
//            updateOrderInfoDelivery(orderInfoDelivery, response);
//            if(response.isFlag()){
//                response.setStatus(1);
//                redisUtil.set(request.getOrderInfoId()+"-"+request.getDeliveryNumber(), response, 3L, TimeUnit.HOURS);
//                return response;
//            }
//        } catch (Exception e) {
//            log.info("--------------- 请求万维易源查询快递信息失败结果: {} ---------------", e);
//        }

        return null;
    }

    private String getExpressNo(String deliveryId,String phone) {
        // 顺丰随便拼接个手机号后缀
        if (StringUtils.isNotBlank(deliveryId)&&deliveryId.contains("SF")){
            if (StringUtils.isBlank(phone)){
                return deliveryId+":0132";
            }
            return deliveryId+":"+phone;
        }
        // 其他物流实现 todo
        return deliveryId;
    }

    /**
     * 
     * @author cyz
     * @date 2021/4/12 17:59
     * @param orderInfoId 
     * @return com.zbkj.crmeb.store.model.OrderInfoDelivery
     */
    @Override
    public OrderInfoDelivery selectDeliveryByOrderInfoId(Integer orderInfoId) {
        return dao.selectDeliveryByOrderInfoId(orderInfoId);
    }

    /**
     * 判断物流签收时间
     * @param request
     */
//    @Override
//    public boolean judgeSignIn(OrderInfoDelivery request) {
//        String sign = getSign(request.getDeliveryCode(),request.getDeliveryNumber(),request.getPhone());
//        String url = "";
//        if(StringUtils.isBlank(request.getPhone())){
//            url = "https://route.showapi.com/64-19?com="+request.getDeliveryCode()+"&nu="+request.getDeliveryNumber()+"&showapi_appid="+appId+"&showapi_sign="+sign;
//        }else {
//            url = "https://route.showapi.com/64-19?com="+request.getDeliveryCode()+"&nu="+request.getDeliveryNumber()+"&phone="+request.getPhone()+"&showapi_appid="+appId+"&showapi_sign="+sign;
//        }
//        try {
//            log.info("--------------- 开始请求万维易源查询快递信息 url: {},body:{} ---------------", url , JSONObject.toJSONString(request));
//            JSONObject jsonObject = restTemplateUtil.getData(url);
//            log.info("--------------- 请求万维易源查询快递信息返回结果: {} ---------------", jsonObject);
//            if("-2".equals(jsonObject.get("showapi_res_code").toString()) ){
//                smsService.sendLogisticsMessage();
//            }
//            if(Objects.isNull(jsonObject.get("showapi_res_body"))){
//                return false;
//            }
//            DeliveryResponse response = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("showapi_res_body")), DeliveryResponse.class);
//            // 更新物流API查询结果
//            updateOrderInfoDelivery(request, response);
//            for (String str : response.getData()) {
//                if(str.contains("已签收")){
//                    DeliveryInfo deliveryInfo = JSONObject.parseObject(str, DeliveryInfo.class);
//                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTime(format.parse(deliveryInfo.getTime()));
//                    calendar.add(Calendar.DATE, 3);
////                    calendar.add(Calendar.MINUTE,3);
//                    return calendar.getTime().compareTo(new Date()) < 0;
//                }
//            }
//        } catch (Exception e) {
//            log.info("--------------- 请求万维易源查询快递信息失败结果: {} ---------------", e.getMessage());
//        }
//        return false;
//    }

    @Override
    public OrderDeliveryResponse getOrderDeliveryList(GetOrderDeliveryListRequest request) {
        OrderDeliveryResponse orderDeliveryResponse = new OrderDeliveryResponse();
        //列表数据
        List<OrderDeliveryItemResponse> orderDeliveryItemResponseList = new ArrayList<>();
        GetOrderDeliveryListRequest searchRequest = new GetOrderDeliveryListRequest();
        BeanUtils.copyProperties(request,searchRequest);
        getOrderDeliveryListRequest(searchRequest);
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getLimit());
        //查询子订单
        List<StoreOrderInfo> childOrderList = dao.selectOrderDeliveryListByUnionQuery(searchRequest);
        if(childOrderList != null && childOrderList.size() > 0){
            orderDeliveryItemResponseList = formatOrderDelivery(childOrderList);
        }
        CommonPage<OrderDeliveryItemResponse> orderDeliveryItemResponseCommonPage = CommonPage.restPage(CommonPage.copyPageInfo(page, orderDeliveryItemResponseList));
        orderDeliveryResponse.setList(orderDeliveryItemResponseCommonPage);
        //状态数量
        orderDeliveryResponse.setStatus(
                new OrderDeliveryCountItemResponse(
                        getCount(request, Constants.DELIVERY_STATUS_ALL),
                        getCount(request, Constants.DELIVERY_STATUS_NOT_SHIPPED),
                        getCount(request, Constants.DELIVERY_STATUS_OVERSEAS),
                        getCount(request, Constants.DELIVERY_STATUS_NOT_CROSS)
                )
        );
        //头部数据
        orderDeliveryResponse.setTop(
                new OrderDeliveryTopItemResponse(
                        getCount(request, request.getLogisticsStatus()),
                        getAmount(request, Constants.ORDER_FIRST_PRICE),
                        getAmount(request, Constants.ORDER_SECOND_PRICE),
                        getAmount(request, Constants.ORDER_TAX_PRICE),
                        getAmount(request, Constants.ORDER_ACTUAL_TAX_AND_SECOND_PRICE)
                )
        );
        return orderDeliveryResponse;
    }

    @Override
    public Object batchExtendedLogistics(StoreOrderSendRequest request) {
        if(CollectionUtils.isEmpty(request.getOrderInfoIdList())){
            throw new CrmebException("子订单id集合不能为空");
        }
        if(!Objects.equals(request.getChannel(),2)){
            throw new CrmebException("操作平台参数异常");
        }
        Express express = expressService.info(Integer.parseInt(request.getExpressId()));
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.list(Wrappers.lambdaQuery(StoreOrderInfo.class).in(StoreOrderInfo::getId, request.getOrderInfoIdList()));
        if(storeOrderInfoList.stream().anyMatch(e -> e.getStatus() != Constants.ORDER_STATUS_H5_SPIKE)){
            throw new CrmebException("部分订单不是待收货状态，导致增段失败，请重新选择");
        }
        if(storeOrderInfoList.stream().anyMatch(e-> e.getLogisticsType() !=1 && !e.getLogisticsType().equals(request.getLogisticsType()))){
            throw new CrmebException("部分订单物流方式不一致，导致增段失败，请重新选择");
        }
        QueryWrapper<OrderInfoDelivery> queryWrapper = new QueryWrapper<>();
        List<OrderInfoDelivery> orderInfoDeliveryList = this.list(queryWrapper.in("order_info_id", request.getOrderInfoIdList()).groupBy("order_info_id").select("order_info_id,MAX(level) as level"));
        Map<Integer, Integer> map = orderInfoDeliveryList.stream().collect(Collectors.toMap(OrderInfoDelivery::getOrderInfoId, OrderInfoDelivery::getLevel));
        List<OrderInfoDelivery> list = new ArrayList<>();
        List<StoreOrderStatus> statusList = new ArrayList<>();
        for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
            OrderInfoDelivery delivery = new OrderInfoDelivery();
            delivery.setOrderInfoId(storeOrderInfo.getId());
            delivery.setDeliveryCompany(express.getName());
            delivery.setDeliveryNumber(request.getExpressCode());
            delivery.setName(request.getName());
            delivery.setDeliveryCode(express.getCode());
            delivery.setPhone(request.getPhone());
            delivery.setExpressId(Integer.parseInt(request.getExpressId()));
            delivery.setLogisticsStage(request.getLogisticsStage());
            delivery.setLevel(map.get(storeOrderInfo.getId())+1);
            delivery.setChannel(request.getChannel());
            list.add(delivery);
            //物流增段
            StoreCartResponse response = JSON.parseObject(storeOrderInfo.getInfo(),StoreCartResponse.class);
            String message = Constants.ORDER_LOG_ADD_MESSAGE_EXPRESS.replace("{storeName}",response.getProductInfo().getStoreName()).replace("{suk}",response.getProductInfo().getAttrInfo().getSuk()).replace("{channel}","物流部门").replace("{deliveryName}", express.getName()).replace("{deliveryCode}", request.getExpressCode());
            StoreOrderStatus storeOrderStatus = new StoreOrderStatus();
            storeOrderStatus.setOid(storeOrderInfo.getOrderId());
            storeOrderStatus.setOrderNumber(storeOrderInfo.getChildOrderNumber());
            storeOrderStatus.setChangeType(Constants.ORDER_LOG_EXPRESS);
            storeOrderStatus.setChangeMessage(message);
            storeOrderStatus.setCreateTime(DateUtil.nowDateTime());
            statusList.add(storeOrderStatus);
            storeOrderInfo.setLogisticsType(request.getLogisticsType());
        }
        boolean batch = saveOrUpdateBatch(list);
        if(batch){
            storeOrderInfoService.updateBatchById(storeOrderInfoList);
            storeOrderStatusService.saveBatch(statusList);
        }
        return batch;
    }

    @Override
    public Map<Integer, List<OrderInfoDelivery>> getOrderDeliveryInfoList(Integer id) {
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.list(Wrappers.lambdaQuery(StoreOrderInfo.class).eq(StoreOrderInfo::getOrderId, id));
        if (CollectionUtils.isEmpty(storeOrderInfoList)) {
            return null;
        }
        List<OrderInfoDelivery> orderInfoDeliveryList = this.list(Wrappers.lambdaQuery(OrderInfoDelivery.class).eq(OrderInfoDelivery::getChannel, 2).in(OrderInfoDelivery::getOrderInfoId, storeOrderInfoList.stream().map(StoreOrderInfo::getId).collect(Collectors.toList())));
        return orderInfoDeliveryList.stream().collect(Collectors.groupingBy(OrderInfoDelivery::getOrderInfoId));
    }

    public List<StoreOrderInfo> getLogisticsList(GetOrderDeliveryListRequest request, PageParamRequest pageParamRequest) {
        getOrderDeliveryListRequest(request);
        PageHelper.startPage(request.getPage(), request.getLimit());
        return dao.selectOrderDeliveryListByUnionQuery(request);
    }

    private BigDecimal getAmount(GetOrderDeliveryListRequest request, String type) {
        GetOrderDeliveryListRequest searchRequest = new GetOrderDeliveryListRequest();
        BeanUtils.copyProperties(request,searchRequest);
        searchRequest.setPriceType(type);
        getOrderDeliveryListRequest(searchRequest);
        return dao.getSumPriceByCondition(searchRequest);
    }

    private Integer getCount(GetOrderDeliveryListRequest request, String status) {
        GetOrderDeliveryListRequest searchRequest = new GetOrderDeliveryListRequest();
        BeanUtils.copyProperties(request,searchRequest);
        searchRequest.setLogisticsStatus(status);
        getOrderDeliveryListRequest(searchRequest);
        return dao.selectOrderDeliveryCountByCondition(searchRequest);
    }

    private List<OrderDeliveryItemResponse> formatOrderDelivery(List<StoreOrderInfo> childOrderList) {
        Map<Integer, List<StoreOrderInfo>> childOrderMap = childOrderList.stream().collect(Collectors.groupingBy(StoreOrderInfo::getOrderId));
        Set<Integer> orderIdList = childOrderList.stream().map(StoreOrderInfo::getOrderId).collect(Collectors.toSet());
        List<StoreOrder> storeOrderList = storeOrderService.list(Wrappers.lambdaQuery(StoreOrder.class).in(StoreOrder::getId, orderIdList).orderByDesc(StoreOrder::getId));
        List<ChannelMerchant> merList = channelMerchantService.list(Wrappers.lambdaQuery(ChannelMerchant.class).in(ChannelMerchant::getId, storeOrderList.stream().map(StoreOrder::getMerId).distinct().collect(Collectors.toList())));
        Map<Integer, ChannelMerchant> merMap = merList.stream().collect(Collectors.toMap(ChannelMerchant::getId, e -> e));
        //供应商信息
        Set<Integer> actualSupplierIdList = childOrderList.stream().filter(e->e.getSuppliersId() != null).map(StoreOrderInfo::getActualSupplierId).collect(Collectors.toSet());
        List<Supplier> supplierList = supplierService.list(Wrappers.lambdaQuery(Supplier.class).in(Supplier::getId, actualSupplierIdList));
        Map<Integer, String> supplierMap = supplierList.stream().collect(Collectors.toMap(Supplier::getId, Supplier::getSuppliersName));
        List<OrderDeliveryItemResponse> orderDeliveryItemResponseArrayList  = new ArrayList<>();
        for (StoreOrder storeOrder : storeOrderList) {
            OrderDeliveryItemResponse orderDeliveryItemResponse = new OrderDeliveryItemResponse();
            BeanUtils.copyProperties(storeOrder, orderDeliveryItemResponse);
            orderDeliveryItemResponse.setMerName(merMap.get(storeOrder.getMerId()).getChannelName());
            //下单用户
            orderDeliveryItemResponse.setOrderCreateName(storeOrder.getCreateName());
            //子订单信息
            List<StoreOrderInfoVo> storeOrderInfoVoList = new ArrayList<>();
            List<StoreOrderInfo> storeOrderInfoList = childOrderMap.get(storeOrder.getId());
            for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
                StoreOrderInfoVo storeOrderInfoVo = new StoreOrderInfoVo();
                BeanUtils.copyProperties(storeOrderInfo, storeOrderInfoVo, "info");
                storeOrderInfoVo.setInfo(JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class));
                if(storeOrderInfo.getActualSupplierId() != null){
                    storeOrderInfoVo.setActualSupplierName(supplierMap.get(storeOrderInfo.getActualSupplierId()));
                }
                storeOrderInfoVo.setActualTaxAndSecondPrice(storeOrderInfo.getTaxTaxesPrice()
                        .add(storeOrderInfo.getTaxInlandDeliveryPrice())
                        .add(storeOrderInfo.getTaxInternationalPrice())
                        .add(storeOrderInfo.getTaxTurnInlandPrice()));
                storeOrderInfoVoList.add(storeOrderInfoVo);
            }
            orderDeliveryItemResponse.setStoreOrderInfoVoList(storeOrderInfoVoList);
            orderDeliveryItemResponseArrayList.add(orderDeliveryItemResponse);
        }
        return orderDeliveryItemResponseArrayList;
    }

    private void getOrderDeliveryListRequest(GetOrderDeliveryListRequest request) {
        request.setMerIds(systemAdminService.getAdminMerIds());
        if(StringUtils.isNotBlank(request.getDateLimit())) {
            dateLimitUtilVo dateLimitUtilVo = DateUtil.getDateLimit(request.getDateLimit());
            request.setStartTime(dateLimitUtilVo.getStartTime());
            request.setEndTime(dateLimitUtilVo.getEndTime());
        }
        String where = " 1 = 1";
        if(null != request.getLogisticsStatus()){
            switch (request.getLogisticsStatus()){
                case Constants.DELIVERY_STATUS_ALL:
                    where += " and b.logistics_type != 0 ";
                    if (StringUtils.isBlank(request.getOrderNumber())) {
                        where += "or c.status != 6 ";
                    }
                    break;
                case Constants.DELIVERY_STATUS_OVERSEAS:
                    where += " and b.logistics_type = 2 ";
                    break;
                case Constants.DELIVERY_STATUS_NOT_CROSS:
                    where += " and b.logistics_type = 3 ";
                    break;
                case Constants.DELIVERY_STATUS_NOT_SHIPPED:
                    where += " and (b.logistics_type = 1 or b.autonomous = 0) and b.status = 1 ";
                    if (StringUtils.isBlank(request.getOrderNumber())) {
                        where += "or c.status = 1 ";
                    }
                    break;
                default:
                    throw new CrmebException("物流状态参数异常");
            }
        }
        if (StringUtils.isNotBlank(request.getOrderNumber())) {
            request.setOrderNumbers(CrmebUtil.stringToArrayStr(request.getOrderNumber()));
            request.setOrderNumber(null);
        }
        request.setWhere(where);
    }

    private String getSign(String com, String deliveryNumber, String phone){
        String signStr = "";
        if(StringUtils.isBlank(phone)){
            signStr = "com"+com+"nu"+deliveryNumber+"showapi_appid"+appId+secret;
        }else {
            signStr = "com"+com+"nu"+deliveryNumber+"phone"+phone+"showapi_appid"+appId+secret;
        }
        String sign= null;
        try {
            sign = DigestUtils.md5Hex(signStr.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("万维生成加密sign失败,"+e);
        }
        return sign;
    }

    /**
     * 物流信息参数转换
     * @param orderInfoDelivery
     * @return
     */
    private DeliveryResponse convertOrderInfoDelivery(OrderInfoDelivery orderInfoDelivery) {
        DeliveryResponse response = new DeliveryResponse();
        response.setData(JSONObject.parseObject(orderInfoDelivery.getData(), String[].class));
        response.setExpSpellName(orderInfoDelivery.getDeliveryCode());
        response.setExpTextName(orderInfoDelivery.getDeliveryCompany());
        response.setMailNo(orderInfoDelivery.getDeliveryNumber());
        response.setLogo(orderInfoDelivery.getLogo());
        response.setTel(orderInfoDelivery.getTel());
        response.setFlag(!Objects.isNull(orderInfoDelivery.getQueryFlag()) && orderInfoDelivery.getQueryFlag());
        response.setStatus(orderInfoDelivery.getStatus());
        return response;
    }

    /**
     * @description  更新物流API查询结果
     * @author lvmd
     * @param orderInfoDelivery  物流信息
     * @param response  API返回结果
     * @return void
     * @exception
     * @date 2022/1/4 17:48
     */
    private void updateOrderInfoDelivery(OrderInfoDelivery orderInfoDelivery, DeliveryResponse response) {
        boolean signStatus = Arrays.stream(response.getData()).anyMatch(str -> str.contains("已签收"));

        orderInfoDelivery.setQueryFlag(response.isFlag());
        // 跟返回值保持一致
        orderInfoDelivery.setStatus(response.isFlag() ? 1 : response.getStatus());
        orderInfoDelivery.setSignStatus(signStatus ? 1 : 0);
        orderInfoDelivery.setLogo(response.getLogo());
        orderInfoDelivery.setTel(response.getTel());
        orderInfoDelivery.setQueryTime(new Date());
        orderInfoDelivery.setData(JSON.toJSONString(response.getData()));

        dao.updateById(orderInfoDelivery);
    }

}

